import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 0 // 超时时间，单位毫秒ms,0为不超时，但是浏览器策略可能导致默认有超时时间，依旧会超时
})

// 请求 拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // 让每个请求都携带token
      // ['TAG-MANAGER-TOKEN'] 是一个自定义的Token名字，WGSS=文稿送审
      config.headers['TAG-MANAGER-TOKEN'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应 拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const result = response.data //response.data = (java) Result<T>
    console.log('后端返回数据:' + JSON.stringify(result))
    // if the custom code is not 1, it is judged as an error.
    if (result.code !== 1) {
      Message({
        message: result.message || '请求出错，请联系管理员',
        type: 'error',
        duration: 5 * 1000
      })

      // 50000 Token expired;
      if (result.code === 50000) {
        // to re-login
        MessageBox.confirm('登录已过期，您可以点击取消留在此页，或重新登陆', '登录过期提醒', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //若重新登陆，则重置token
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(result.message || 'Error'))
    } else {
      return result
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
